//
//  GZNetManager.m
//  GongZheng
//
//  Created by huan on 2018/4/27.
//  Copyright © 2018年 huan. All rights reserved.
//

#import "GZNetManager.h"

typedef void (^SuccessResultBlock)(id obj);
typedef void (^FailureResultBlock)(NSError *error);

static BOOL _networkReachability;

@implementation GZNetManager

+ (instancetype)defaultManager {
    
    static GZNetManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [self manager];
        [manager.requestSerializer setValue:@"IOS/ifsage" forHTTPHeaderField:@"X-Equipment"];
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 20.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        // 添加cookie
        NSArray * firstCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        for (NSHTTPCookie * cookie in firstCookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
        }
//        NSHTTPCookie * cookie = [[NSHTTPCookie alloc] initWithProperties:[[HOUserModel sharedInstance] cookie]];
//        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    });
    
    return manager;
}

//+ (void)stopTask{
//    [[HONetManager defaultManager] invalidateSessionCancelingTasks:NO];
//}

+ (void)netWorkReachability {
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: //未知信号
                
            case AFNetworkReachabilityStatusReachableViaWWAN: //手机信号
                
            case AFNetworkReachabilityStatusReachableViaWiFi: //WiFi信号
                _networkReachability = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable: { //没有信号
                _networkReachability = NO;
                [MBProgressHUD showError:@"当前找不到可用的网络"];
                break;
            }
            default:
                _networkReachability = NO;
                break;
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

+ (void)GET:(NSString *)urlString resultBlock:(GZNetWrokResultBlock)resultBlock {
    [[GZNetManager defaultManager] third:@"GET" URL:urlString params:nil resultBlock:^(NSDictionary *dataDictionary, NSString *errorString) {
        resultBlock(dataDictionary, errorString);
    }];
}

+ (void)DESPOST:(NSString *)urlString parameters:(NSDictionary *)params resultBlock:(GZNetWrokResultBlock)resultBlock {
    HOLog(@"\n{\n  url: %@\n  param: %@\n}",urlString,params);
    [[GZNetManager defaultManager] third:@"POST" URL:urlString params:params resultBlock:^(NSDictionary *dataDictionary, NSString *errorString) {
        resultBlock(dataDictionary, errorString);
    }];
}

+ (void)TDESPOST:(NSString *)urlString parameters:(NSDictionary *)params resultBlock:(GZNetWrokResultBlock)resultBlock {
    HOLog(@"\n{\n  url: %@\n  param: %@\n}",urlString,params);
//    NSDictionary *encryptDict = [self changeToTDESDictionaryWithDictionary:params];
    [[GZNetManager defaultManager] third:@"POST" URL:urlString params:params resultBlock:^(NSDictionary *dataDictionary, NSString *errorString) {
        resultBlock(dataDictionary, errorString);
    }];
}

/**
 *  获取直接传入网络的字典（根据参数列表）
 *
 *  @param dictionary 传入的参数
 *
 *  @return 获得的结果字典
 */
//+ (NSDictionary *)changeToTDESDictionaryWithDictionary:(NSDictionary *)dictionary {
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
//    NSString * dicString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSString *seString = [NSString tripleEncryptText:dicString];
//    NSDictionary *  lastDic = [NSDictionary dictionaryWithObjectsAndKeys:seString,@"ciphertext", nil];
//    return lastDic;
//}

- (void)third:(NSString *)method URL:(NSString *)urlString params:(id)params resultBlock:(GZNetWrokResultBlock)resultBlock {
    //    if (!_networkReachability) {
    //        [MBProgressHUD showError:@"当前找不到可用的网络"];
    //        return;
    //    }
    
    [self second:method URL:urlString params:params success:^(id obj) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
        // NSData转为NSString
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        NSLog(@"the result for ------>  %@  \n =======> \n%@\n",urlString,jsonStr);
        NSString *returnStatus = [NSString stringWithFormat:@"%@",[obj objectForKey:@"returnStatus"]];
        if ([returnStatus isEqualToString:@"200"]) { // 成功
            resultBlock([obj objectForKey:@"returnInformation"], nil);
        }else  if ([returnStatus isEqualToString:@"1"]){ //出现错误
            resultBlock(nil, [obj objectForKey:@"returnReason"]);
        }else  if ([returnStatus isEqualToString:@"100"]){ //出现错误
            resultBlock(nil, [obj objectForKey:@"returnReason"]);
        }else if ([returnStatus isEqualToString:@"2"]){ //系统异常
            resultBlock(nil, [obj objectForKey:@"returnReason"]);
        }else if([returnStatus isEqualToString:@"3"] ){
            //            [[HOUserModel sharedInstance] cleanUserModel];;
            resultBlock(nil, @"当前用户操作异常，已被强制退出。");
        }else if ([returnStatus isEqualToString:@"4"]){
            //            [[NSNotificationCenter defaultCenter] postNotificationName:kIFSHOULDUPGRADED object:nil];//强制升级
        }else if ([returnStatus isEqualToString:@"-2"] || [returnStatus isEqualToString:@"-1"]){
            NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[obj objectForKey:@"returnInformation"], returnStatus, nil];
            resultBlock(dic, nil);
        }else{
            resultBlock(nil, [obj objectForKey:@"remarks"]);
        }
    } failure:^(NSError *error) {
        resultBlock(nil, [error.userInfo objectForKey:@"reason"]);
    }];
}

- (void)second:(NSString *)method URL:(NSString *)urlString params:(id)params success:(SuccessResultBlock)success failure:(FailureResultBlock)failure {
    [self startRequestWithHTTPMethod:method URL:urlString params:params success:^(id obj) {
        self.numsOfOutTime = 0;
        if (!obj) {
            NSDictionary * reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"接收数据错误",@"reason", nil]; //没有接受到返回数据
            NSError * error = [NSError errorWithDomain:@"com.manman.use" code:-1 userInfo:reasonDic];
            failure(error);
            
            return;
        }
        success(obj);
    } failure:^(NSError *error) {
        NSDictionary * reasonDic = nil;
        if (error.code == -1012) {
            reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"未能接收到数据,请检查网络",@"reason" ,nil];
        }
        if (error.code == -1011) {
            NSHTTPURLResponse * response = [error.userInfo objectForKey:@"com.alamofire.serialization.response.error.response"];
            NSInteger codeNumber = response.statusCode;
            if (codeNumber == 404){ //codeNumber == 500  404(找不到地址) 405(方法错误)  401(未授权)
                reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"找不到地址",@"reason" ,nil];
            }else if (codeNumber == 405){
                reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"方法错误",@"reason" ,nil];
            }else if (codeNumber == 401){
                reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"未授权",@"reason" ,nil];
            }else{
                reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"内部服务器错误",@"reason" ,nil];
            }
        }
        if (error.code == -1009) {
            reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"网络已断开",@"reason" ,nil];
        }//codeNumber == 0
        if (error.code == 3840) {
            reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"未能接收到返回数据",@"reason" ,nil];
        }//未验证
        if (error.code == -1004) {
            reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"未能连接到服务器",@"reason" ,nil];
        }//未验证
        if (error.code == -1001) {
            reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"请求超时",@"reason" ,nil];
        }//未验证codeNumber == 408
        if (reasonDic == nil) {
            reasonDic = [NSDictionary dictionaryWithObjectsAndKeys:error.localizedDescription,@"reason" ,nil];
        }
        //#warning 系统维护
        //        self.numsOfOutTime ++;
        //        if (self.numsOfOutTime >= 3) {
        //            [[NSNotificationCenter defaultCenter] postNotificationName:@"" object:nil];
        //            self.numsOfOutTime = 0;
        //        }
        NSError * returnError = [NSError errorWithDomain:@"com.eage.use" code:-1 userInfo:reasonDic];
        failure(returnError);
    }];
}

- (void)startRequestWithHTTPMethod:(NSString *)method URL:(NSString *)urlString params:(id)params success:(SuccessResultBlock)success failure:(FailureResultBlock)failure {
    if ([method isEqualToString:@"GET"]) {
        [self GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(error);
        }];
    }else if ([method isEqualToString:@"POST"]) {
        [self POST:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(error);
        }];
    }
}


@end
